<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\enum\ConfigEnum;
use app\enum\OceanEnum;
use app\service\fetch\OceanFetchService;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;

class OeImageListWork extends BaseWork
{
    public const REDIS_TASK_KEY = ConfigEnum::CACHE_CONFIG[OceanEnum::LIST_CONFIG_KEY]['img'];

    protected function configure()
    {
        // 指令配置
        $this->setName('oe_image_list_work');
        // 设置参数
        $this->setDescription('拉取巨量增量图片素材列表');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        $this->getOutputMessage('巨量引擎-拉取巨量图片素材列表开始');
        try {
            $redis = Cache::store('redis')->handler();
            $st = time() + 5 * 60;
            while (time() < $st) {
                $advertiserId = $redis->lPop(self::REDIS_TASK_KEY);
                if (! $advertiserId) {
                    usleep(500000);
                    continue;
                }
                $this->getOutputMessage('巨量引擎-拉取巨量图片素材列表开始,账户id:' . $advertiserId);
                $res = OceanFetchService::fetchImageList($advertiserId);
                if (! $res) {
                    $this->getOutputMessage('巨量引擎-拉取巨量图片素材列表失败,账户id:' . $advertiserId . ' 错误：' . OceanFetchService::getError(0));
                } else {
                    $this->getOutputMessage('巨量引擎-拉取巨量图片素材列表成功,账户id:' . $advertiserId);
                }
            }
        } catch (\Exception $e) {
            $this->getOutputMessage('巨量引擎-拉取巨量图片素材列表失败');
            echo $e->getLine() . PHP_EOL;
            echo $e->getFile() . PHP_EOL;
            echo $e->getTraceAsString() . PHP_EOL;
        }
        $this->getOutputMessage('巨量引擎-拉取巨量图片素材列表结束');
    }
}
